package com.action;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.*;
import com.service.*;
import com.util.ValidateHelper;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/businessStaff")
public class BusinessStaffAction {

    @Autowired
    private BusinessStaffService businessStaffService;

    @Autowired
    private BusinessStaffShenpiService businessStaffShenpiService;

    @Autowired
    private StaffService staffService;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private QiyeService qiyeService;


    @Value("${upload.dir}")
    private String upload ;

    @Value("${upload.tmp.dir}")
    private String tmp ;

    /**
     * 商户员工列表
     * @param name  商户名称
     * @param page  页数
     * @param limit 每页条数
     * @return
     */
    @RequestMapping("/getBusinessStaffList")
    public ResponseBean getBusinessList(String name, @RequestParam(required = false) String businessId,
                                        @RequestParam(required = false) String qyId, @RequestParam(required = false) Integer status,
                                        @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit){
        IPage iPage = businessStaffService.getBusinessStaffList(name, businessId, qyId, status, page, limit);
        return new ResponseBean(0,iPage.getTotal(),"成功", iPage.getRecords());
    }


    /**
     * 新增商户员工
     * @return
     */
    /*@RequestMapping("/addBusinessStaff")
    public ResponseBean addBusinessStaff(@RequestBody BusinessStaff businessStaff) {
        businessStaff.setCreateTime(new Date());
        businessStaff.setStatus(1);
        int c = businessStaffService.selectBh(businessStaff.getBh());
        if (c != 0) {
            return new ResponseBean(500, 1, "员工编号已存在");
        }
        if (businessStaffService.save(businessStaff)) {
            return new ResponseBean(200, 1, "新增成功");
        }

        return new ResponseBean(500, 1, "新增失败");
    }*/

    /*@RequestMapping("/updateBusinessStaff")
    public ResponseBean updateBusinessStaff(@RequestBody BusinessStaff businessStaff){

        int j = businessStaffService.selectBh(businessStaff.getBh());
        int k = businessStaffService.selectBhId(businessStaff.getBh(),businessStaff.getId());
        if(j>=1 && k==0){
            return new ResponseBean(500,1,"重复","员工编号重复");
        }
        if(businessStaffService.updateById(businessStaff)){
            return new ResponseBean(200,1,"修改成功","修改成功");
        }
        return new ResponseBean(500,1,"修改失败");
    }*/

    /**
     * 修改商户员工状态
     */
    /*@RequestMapping("/upStatus")
    public ResponseBean changeStatus(String id,Integer status) {
        BusinessStaff businessStaff = new BusinessStaff();
        businessStaff.setId(id);
        businessStaff.setStatus(status);
        if(businessStaffService.updateById(businessStaff)){
            return new ResponseBean(0,1,"修改状态成功");
        }
        return new ResponseBean(1,1,"修改状态失败");
    }*/

    /**
     * 获取商户员工审批记录
     * @param name 关键字：员工姓名
     * @param businessId 商户ID
     * @param staffStatus 员工申请状态：0离职、1入职
     * @param status 审批状态：0审批中、1审批完成
     * @param result 审批结果：0驳回、1通过
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/getBusinessStaffSp")
    public ResponseBean getBusinessStaffSp (String name, String businessId, String staffStatus, String status, String result,
                                            @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        IPage iPage = businessStaffShenpiService.getBusinessStaffSp(name, businessId, staffStatus, status, result, page, limit);
        return new ResponseBean(0,iPage.getTotal(),"成功", iPage.getRecords());
    }

    /**
     * 审批商户员工
     * @param id 审批记录ID
     * @param result 审批结果：0拒绝、1同意
     * @param staffStatus 申请类型：0离职、1入职
     * @return
     */
    @RequestMapping("/shenpi")
    public ResponseBean shenpiStaff (String id, Integer result, Integer staffStatus, HttpServletRequest request) {
        // 参数校验
        if (ValidateHelper.isEmptyString(id) || null == result || null == staffStatus) {
            return ResponseBean.error("必填参数为空");
        }

        BusinessStaffShenpi businessStaffShenpi = businessStaffShenpiService.getById(id);
        // 审批记录检查
        if (null == businessStaffShenpi) {
            return ResponseBean.error("审批记录不存在");
        }
        if (businessStaffShenpi.getStatus() == 1) {
            return ResponseBean.error("该审批记录已被处理");
        }

        // 同意离职
        ResponseBean x = lzProcess(result, staffStatus, businessStaffShenpi);
        if (x != null) return x;

        // 同意入职
        ResponseBean y = rzProcess(result, staffStatus, businessStaffShenpi);
        if (y != null) return y;

        // 更新审批记录
        businessStaffShenpi.setStatus(1);
        businessStaffShenpi.setResult(result);
        businessStaffShenpi.setShenpiTime(new Date());
        businessStaffShenpi.setShenpiUser("");
        businessStaffShenpiService.updateById(businessStaffShenpi);
        return ResponseBean.ok("操作成功");
    }

    /**
     * 入职处理
     * @param result 处理结果：0拒绝、1同意
     * @param staffStatus  申请类型：0离职、1入职
     * @param businessStaffShenpi 审批值对象
     * @return
     */
    @Nullable
    private ResponseBean rzProcess(Integer result, Integer staffStatus, BusinessStaffShenpi businessStaffShenpi) {
        if (staffStatus == 1 && result == 1) {
            // 根据证件号码获取员工
            Staff staff = staffService.getStaffInfoBySfz(businessStaffShenpi.getStaffSfz());

            String qyId = "";
            Business business = businessService.getById(businessStaffShenpi.getBusinessId());
            // 商户不为空
            if (!ValidateHelper.isEmpty(business)) {
                if (ValidateHelper.isEmptyString(business.getWyid())) {
                    return ResponseBean.error("商户所属物业为空");
                }
                // 根据审批表员工物业ID查询该物业下所有企业
                List<Qiye> qiyeList = qiyeService.selectQiyes(business.getWyid());
                if (ValidateHelper.isNotEmptyCollection(qiyeList)) {
                    for (Qiye qiye : qiyeList) {
                        // 判断物业下面有没有与商户名称重名的企业
                        if (qiye.getQyname().equals(business.getName())) {
                            qyId = qiye.getId();
                            break;
                        }
                    }
                }

                // 企业ID不为空，表示物业下存在与商户重名的企业，直接将企业ID赋值给用户
                if (ValidateHelper.isEmptyString(qyId)) {
                    Qiye qiye = new Qiye();
                    qiye.setQyname(business.getName());
                    qiye.setWyID(business.getWyid());

//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    qiye.setCreateTime(new Date());
                    qiye.setShstatus(1);
                    qiye.setStatus(1);
                    if (ValidateHelper.isNotEmptyString(business.getAddress())) {
                        qiye.setAddress(business.getAddress());
                    }
                    if (qiyeService.save(qiye)) {
                        qyId = qiye.getId();
                    }
                }
            }

            // 根据证件号查询员工，不为空则是老员工
            if (staff != null) {
                // 查询员工是否已经在商户员工表存在
                BusinessStaff businessStaff = businessStaffService.getBusinessStaffByStaffId(staff.getId());
                if (null != businessStaff) {
                    // 状态为1表示在职
                    if (businessStaff.getStatus() == 1) {
                        return ResponseBean.error("入职员工已存在");
                    }else {
                        // 状态为0 表示离职，重新入职
                        businessStaff.setStatus(1);
                        businessStaffService.updateById(businessStaff);
                    }
                }else {
                    // 商户员工不存在，表示老员工入职
                    businessStaff = new BusinessStaff();
                    businessStaff.setBusinessId(businessStaffShenpi.getBusinessId());
                    businessStaff.setStaffId(staff.getId());
                    businessStaff.setStatus(1);
                    businessStaff.setCreateTime(new Date());
                    businessStaff.setZmPicture(businessStaffShenpi.getZmPicture());
                    businessStaffService.save(businessStaff);
                }

                if (ValidateHelper.isNotEmptyString(staff.getQyID())) {
                    Qiye qiye = qiyeService.getById(staff.getQyID());
                    if (null != qiye) {
                        if (!qiye.getQyname().equals(business.getName())) {
                            staff.setQyID(qyId);
                        }
                    }
                }else {
                    staff.setQyID(qyId);
                }
                staffService.updateById(staff);

            }else {
                // 员工为空，表示新员工入职
                staff = new Staff();
                staff.setSfz(businessStaffShenpi.getStaffSfz());
                staff.setName(businessStaffShenpi.getStaffName());
                if (ValidateHelper.isNotEmptyString(businessStaffShenpi.getStaffPicture())) {
                    staff.setPicture(businessStaffShenpi.getStaffPicture());
                    FileUtil.copy(tmp + businessStaffShenpi.getStaffPicture(), upload, true) ;
                }

                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
                staff.setCstime(format.format(businessStaffShenpi.getStaffCsTime()));
                staff.setZhiye(businessStaffShenpi.getStaffZhiye());
                staff.setGuoji(businessStaffShenpi.getStaffGuoji());
                if (ValidateHelper.isNotEmptyString(businessStaffShenpi.getStaffPhone())) {
                    staff.setPhone(businessStaffShenpi.getStaffPhone());
                }
                if (ValidateHelper.isNotEmptyString(businessStaffShenpi.getStaffAddress())) {
                    staff.setAddress(businessStaffShenpi.getStaffAddress());
                }
                staff.setRztime(businessStaffShenpi.getStaffRzTime());
                staff.setSex(businessStaffShenpi.getStaffSex());
                staff.setCreatetime(new Date());
                staff.setStatus(1);
                staff.setJfstatus(0);
                staff.setShstatus(1);
                staff.setRztime(new Date());
                staff.setQyID(qyId);
                try {
                    // 生成员工编号
                    Map<String, String> resultMap = staffService.genBh(staff);
                    if (resultMap.containsKey("error")) {
                        return ResponseBean.error("审批失败，" + resultMap.get("error"));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return ResponseBean.error("审批失败，无法生成员工编号");
                }

                if (staffService.save(staff)) {
                    BusinessStaff businessStaff = new BusinessStaff();
                    businessStaff.setBusinessId(businessStaffShenpi.getBusinessId());
                    businessStaff.setStaffId(staff.getId());
                    businessStaff.setStatus(1);
                    businessStaff.setCreateTime(new Date());
                    businessStaff.setZmPicture(businessStaffShenpi.getZmPicture());
                    businessStaffService.save(businessStaff);

                    // 员工编号回填到审批表
                    if (ValidateHelper.isEmptyString(businessStaffShenpi.getStaffBh())) {
                        businessStaffShenpi.setStaffBh(staff.getBh());
                    }
                }
            }
        }
        return null;
    }

    /**
     * 离职处理
     * @param result 处理结果：0拒绝、1同意
     * @param staffStatus  申请类型：0离职、1入职
     * @param businessStaffShenpi 审批值对象
     * @return
     */
    @Nullable
    private ResponseBean lzProcess(Integer result, Integer staffStatus, BusinessStaffShenpi businessStaffShenpi) {
        if (staffStatus == 0 && result == 1) {
            Staff staff = staffService.getStaffByBh(businessStaffShenpi.getStaffBh());
            if (null == staff) {
                return ResponseBean.error("离职员工不存在");
            }
            BusinessStaff businessStaff = businessStaffService.getBusinessStaffByStaffId(staff.getId());
            if (null == businessStaff) {
                return ResponseBean.error("离职商户员工不存在");
            }
            if (staffStatus == businessStaff.getStatus()) {
                return ResponseBean.error("该员工已离职");
            }
            // 更新状态为离职
            businessStaff.setStatus(0);
            businessStaffService.updateById(businessStaff);
        }
        return null;
    }

}
